import datetime
import json
import random

import re
from unittest import result

from flask import current_app
from flask import make_response, jsonify
from flask import request
from flask import session

from info import redis_store, db
from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.utils.captcha.captcha import captcha
from info.utils.response_code import RET
from . import passport_blue

@passport_blue.route('/image_code')
def image_code():
    cur_id = request.args.get('cur_id')
    pre_id = request.args.get('pre_id')

    if not cur_id:
        return '参数不全'

    if pre_id:
        redis_store.delete('image_code:%s' % pre_id)

    name , text,image_code = captcha.generate_captcha()

    redis_store.set('image_code:%s' %cur_id,text,300)


    response = make_response(image_code)
    response.headers['Content-Type'] = 'image/png'


    return response


@passport_blue.route('/sms_code',methods=['POST'])
def sms_code():

    # json_data= request.data
    # dict_data = json.loads(json_data)
    dict_data = request.json


    mobile = dict_data.get('mobile')
    image_code = dict_data.get('image_code')
    image_code_id = dict_data.get('image_code_id')

    if not all([mobile,image_code,image_code_id]):
        return jsonify(errno=RET.NODATA,errmsg='参数不全')

    if not re.match(r'1[3-9]\d{9}',mobile):
        return jsonify(errno=RET.PARAMERR,errmsg='手机号格式不正确')

    redis_image_code = redis_store.get('image_code:%s' % image_code_id)
    if not redis_image_code:
        return jsonify(errno=RET.PARAMERR,errmsg='图片验证码已过期')

    if image_code.lower() != redis_image_code.lower():
        return jsonify(errno=RET.DATAERR,errmsg='图片验证码填写错误')

    sms_code = '%06d' % random.randint(0,999999)

    current_app.logger.debug('sms_code: %s' % sms_code)

    # ccp = CCP()

    # ccp.send_template_sms(mobile, [sms_code, 5], 1)
    #
    # if result == -1:
    #     return jsonify(error='',errmsg='发送失败')
    #
    redis_store.set('sms_code: %s' % mobile,sms_code,300)
    #
    return jsonify(errno=RET.OK, errmsg='发送成功')


@passport_blue.route('/register',methods=['POST'])
def register():

    dict_data = request.json

    mobile = dict_data.get('mobile')
    password = dict_data.get('password')
    sms_code = dict_data.get('sms_code')
    print(mobile)

    if not all([mobile,password,sms_code]):
        return jsonify(errno=RET.NODATA,errmsg='参数不全')

    count = User.query.filter(User.mobile == mobile).count()
    if count > 0:
        return jsonify(errno=RET.DATAERR,errmsg='用户已经存在')

    redis_sms_code = redis_store.get('sms_code: %s' % mobile)
    print(redis_sms_code)
    if not  redis_sms_code:
        return jsonify(errno=RET.DATAERR,errmsg='验证码已过期')

    if sms_code != redis_sms_code:
        return jsonify(errno=RET.DATAERR,errmsg='手机验证码不正确')

    try:
        user = User()
        user.nick_name = mobile
        user.password = password
        user.mobile = mobile

        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DATAERR,errmsg='手机验证码不正确')

    return jsonify(error=RET.OK, errmsg='注册成功')


@passport_blue.route('/login', methods=['POST'])
def login():

    dict_data = request.json

    mobile = dict_data.get('mobile')
    password = dict_data.get('password')



    try:
        user = User.query.filter(User.mobile==mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="用户不存在")

    if not user:
        return jsonify(errno=RET.USERERR, errmsg="用户不存在")

    if not user.check_passowrd(password):
        return jsonify(errno=RET.DATAERR,errmsg="密码错误")

    session['user_id'] = user.id
    session['nick_name'] = user.nick_name
    session['mobile'] = mobile

    user.last_login = datetime.datetime.now()

    try:

        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)


    return jsonify(errno=RET.OK, errmsg='OK')

@passport_blue.route('/logout',methods=['POST'])
def logout():
    session.pop('user_id')
    session.pop('nick_name')
    session.pop('mobile')

    return jsonify(errno=RET.OK,errmsg='用户已退出')





